package {
	import flash.display.*;
	import flash.events.*;
	import flash.geom.*;
	import flash.text.*;
	import flash.utils.*;
	import ghostcat.algorithm.traversal.*;
	import ghostcat.display.bitmap.*;
	import ghostcat.manager.*;
	import ghostcat.parse.display.*;

	public class AStarExample extends Sprite {
		private var debugText:TextField;
		private const MAP_WIDTH:int = 10;
		private var mapModel:MapModel;
		private const MAP_HEIGHT:int = 10;
		private var map:Array;
		private var screen:GBitmap;
		private var aStar:Traversal;
		private var playPoint:Point;
		private var path:Array;

		public function AStarExample() {
			RootManager.register(this, 1, 1);
			screen = new GBitmap(new BitmapData(MAP_WIDTH, MAP_HEIGHT));
			screen.enableMouseEvent = true;
			screen.enabledScale = true;
			var _loc_1:int = 5;
			screen.scaleY = 5;
			screen.scaleX = _loc_1;
			addChild(screen);
			debugText = new TextFieldParse(null, new Point(0, 500)).createTextField();
			addChild(debugText);
			this.mapModel = new MapModel();
			this.reset();
			addEventListener(MouseEvent.CLICK, clickHandler);
			addEventListener(Event.ENTER_FRAME, enterframeHandler);
			return;
		} // end function

		private function clickHandler(event:MouseEvent):void {
			var _loc_2:* = getTimer();
			this.path = this.aStar.find(playPoint.clone(), new Point(int(screen.mouseX), int(screen.mouseY)));
			if (!this.path) {
				debugText.text = "无法到达";
			} else {
				debugText.text = "耗时:" + (getTimer() - _loc_2) + "ms";
			}
			return;
		} // end function

		private function enterframeHandler(event:Event):void {
			if (this.path == null || this.path.length == 0) {
				return;
			}
			screen.bitmapData.setPixel(playPoint.x, playPoint.y, 16777215);
			playPoint = this.path.shift() as Point;
			screen.bitmapData.setPixel(playPoint.x, playPoint.y, 16711680);
		} // end function

		private function reset():void {
			var col:int = 0;
			var walkable:Boolean = false;
			this.map = [];
			var row:int = 0;
			while (row < MAP_HEIGHT) {

				map[row] = [];
				col = 0;
				while (col < MAP_WIDTH) {

					walkable = Math.random() < 0.3;
					map[row][col] = walkable;
					screen.bitmapData.setPixel(col, row, walkable ? (0) : (16777215));
					col++;
				}
				row++;
			}
			this.playPoint = new Point();
			screen.bitmapData.setPixel(0, 0, 16711680);
			this.mapModel.map = this.map;
			this.aStar = new AStar(this.mapModel);
		} // end function

	}
}
